package handler

import (
	"io"
	"net/http"
	"strings"

	"github.com/zeromicro/go-zero/rest"
)

const userServiceURL = "http://127.0.0.1:8888"

type UserGateway struct{}

func (g *UserGateway) RegisterRoutes(server *rest.Server) {
	methods := []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete}
	for _, m := range methods {
		server.AddRoute(rest.Route{
			Method:  m,
			Path:    "/user/:path/:path",
			Handler: g.forwardHandler(),
		})
	}
}

func (g *UserGateway) forwardHandler() http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// 获取原始路径
		fullPath := r.URL.Path                              // /user/xxx
		targetPath := strings.TrimPrefix(fullPath, "/user") // /xxx
		if targetPath == "" {
			targetPath = "/" // 防止变成空
		}
		targetURL := userServiceURL + targetPath

		req, _ := http.NewRequest(r.Method, targetURL, r.Body)
		req.Header = r.Header

		resp, err := http.DefaultClient.Do(req)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer resp.Body.Close()

		for k, v := range resp.Header {
			w.Header()[k] = v
		}
		w.WriteHeader(resp.StatusCode)
		io.Copy(w, resp.Body)
	}
}
